package pt.uc.dei.mse.eai.screenScrapping;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * A façade around the Apache HttpClient library, which returns a web page content as a String 
 * @author XPTS929
 *
 */
public class HttpClientUtils {

	/**
	 * 
	 * @param url
	 * 		the web page URL
	 * @return 
	 * 		the web page content as a string
	 * @throws IOException
	 */
	public static String getPage(String url) throws IOException {
		System.out.println("Getting page " + url);

		if (!url.startsWith("http:")) {
			FileReader fr = new FileReader(url);
			BufferedReader br = new BufferedReader(fr);
			StringBuilder sb = new StringBuilder();
			String s;
			while ((s = br.readLine()) != null) {
				sb.append(s);
			}
			return sb.toString();
		}

		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(url);
		HttpResponse response = client.execute(get);
		HttpEntity e = response.getEntity();
		byte[] text = EntityUtils.toByteArray(e);
		return new String(text);
	}

}
